using System;
using JNPF.Basics.Models;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JNPF.Utils;
using System.Transactions;
using Senparc.Weixin.MP.AdvancedAPIs.TemplateMessage;
using NPOI.POIFS.FileSystem;
using NPOI.SS.Formula.Functions;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

namespace JNPF.Basics.Logic
{
    public class CustomerloandetailBll
    {
        private CustomerloandetailIService service = new CustomerloandetailService();

        private UserextendIService userextendService = new UserextendService();


        private CustomerloanIService customerloanIService = new CustomerloanService();


        private CustomerloanIService customerloanService = new CustomerloanService();


        private CustomerbaseIService customerbaseService = new CustomerbaseService();

        private CustomerneedIService customerneedService = new CustomerneedService();

        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        public async Task<CustomerloandetailEntity> GetInfo(int id)
        {
            try
            {
                return await service.GetInfo(id);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }

        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        public async Task<CustomerloandetailEntity> GetInfoByUUID(string uuid)
        {
            try
            {
                return await service.GetInfoByUUID(uuid);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }


        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<CustomerloandetailEntity>> GetPageList(CustomerloandetailListQueryInput input)
        {
            try
            {
                return await service.GetPageList(input);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }

        /// <summary>
        /// 列表（分页）
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<CustomerloandetailListOutput>> GetPageListByCus(CustomerloandetailListQueryInput input)
        {
            try
            {
                return await service.GetPageListByCus(input);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }


        /// <summary>
        /// 企业用户  ===  手机号码对应起来的 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResult<CustomerloandetailListOutput>> GetBusPageList(CustomerloandetailListQueryInput input)
        {
            try
            {
                return await service.GetBusPageList(input);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }


        /// <summary>
        /// 客户经理列表（分页）
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<CustomerloandetailListOutput>> GetCuseBusList(CustomerloandetailListQueryInput input)
        {
            try
            {
                return await service.GetCuseBusList(input);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }


        /// <summary>
        /// 信贷管家   列表（分页）
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<CustomerloandetailListOutput>> GetPagCuseList(CustomerloandetailListQueryInput input)
        {
            try
            {
                return await service.GetPagCuseList(input);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }

        /// <summary>
        /// 列表（分页）
        /// </summary>
        /// <param name="needDetailId">需求Id</param>
        /// <returns></returns>
        public async Task<List<CustomerloandetailListOutputNew>> GetDetialByneedDetailId(int needDetailId)
        {
            try
            {
                return await service.GetDetialByneedDetailId(needDetailId);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }

        }





        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<CustomerloandetailEntity>> GetPageListBySql(CustomerloandetailListQueryInput input)
        {
            try
            {
                return await service.GetPageListBySql(input);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }


        /// <summary>
        /// 列表（分页）
        /// </summary>
        /// <param name="customerLoanUUID">请求参数</param>
        /// <returns></returns>
        public async Task<List<CustomerloandetailEntity>> GetList(string customerLoanUUID)
        {
            try
            {
                return await service.GetList(customerLoanUUID);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }

        /// <summary>
        /// 创建信息
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Create(CustomerloandetailEntity entity)
        {
            try
            {
                entity.CreatorTime = DateTime.Now;
                entity.CreatorUserId = UserProvider.Instance.Get().UserId;
                entity.CreatorUser = UserProvider.Instance.Get().UserName;
                entity.DeleteMark = 0;
                entity.Serialid = Guid.NewGuid().ToString("N");
                return await service.Create(entity);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }


        /// <summary>
        /// 放款
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <param name="input"></param>
        /// <param name="xd">是否续贷</param>
        /// <returns></returns>
        public async Task Lending(CustomerloandetailEntity entity, CustomerloanCrInputNews input, bool xd = false)
        {
            try
            {
                List<PointsdetailsEntity> pointsdetailsEntities = new List<PointsdetailsEntity>();
                List<UserextendEntity> userextendEntities = new List<UserextendEntity>();

                CustomerloanEntity customerloan = await customerloanService.GetInfoByUUId(entity.CustomerLoanUUID);

                CustomerbaseEntity customerbase = await customerbaseService.GetInfo(customerloan.CustomerId.Value);

                CustomerneedEntity customerneedEntity = await customerneedService.GetInfo(customerloan.CustomerNeedId.Value);

                if (customerneedEntity.Type != 1)
                {

                    customerneedEntity.Type = 1;
                }

                //改成已放款
                await customerneedService.Update(customerneedEntity);

                if (!xd)
                {
                    //首先当前状态改成已放款
                    entity.Type = 1;
                }

                entity.LendingDate = input.lendingDate;
                entity.Amount = input.amount;
                entity.Term = input.term;
                entity.Rate = input.rate;
                entity.Method = input.method;
                entity.Detail = input.detail;
                entity.Attachment = input.attachment;

                await service.Update(entity);

            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }

        /// <summary>
        /// 续贷
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task RenewalLoan(CustomerloandetailEntity entity, CustomerloanCrInputNews input)
        {
            try
            {
                CustomerloanEntity customerloanEntity = await customerloanIService.GetInfoByUUId(entity.CustomerLoanUUID);

                customerloanEntity.Number++;

                //续贷结清时间，算期数 
                entity.EndDate = input.endDate; //entity.LendingDate.Value.AddMinutes(entity.Term.ToInt());
                entity.Type = 3; //续贷

                CustomerloandetailEntity customerloandetail = entity.ToJson().ToObject<CustomerloandetailEntity>();
                customerloandetail.Id = null;
                customerloandetail.ParentSerialid = entity.Serialid;
                customerloandetail.Serialid = Guid.NewGuid().ToString("N");
                customerloandetail.CreatorTime = DateTime.Now;
                customerloandetail.CreatorUser = UserProvider.Instance.Get().UserName;
                customerloandetail.CreatorUserId = UserProvider.Instance.Get().UserId;
                customerloandetail.Type = 0;

                await service.Create(entity, customerloanEntity, customerloandetail);

                //续贷直接放款
                customerloandetail = await service.GetInfoBySerialid(customerloandetail.Serialid);

                //再走一下放
                await Lending(customerloandetail, input, true);



            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }

        /// <summary>
        /// 更新信息
        /// </summary>
        /// <param name="id">主键值</param>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Update(int id, CustomerloandetailEntity entity)
        {
            try
            {
                entity.Id = id;
                entity.LastModifyTime = DateTime.Now;
                entity.LastModifyUserId = UserProvider.Instance.Get().UserId;
                return await service.Update(entity);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }

        /// <summary>
        /// 删除信息
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Delete(CustomerloandetailEntity entity)
        {
            try
            {
                entity.DeleteMark = 1;
                entity.DeleteTime = DateTime.Now; ;
                entity.DeleteUserId = UserProvider.Instance.Get().UserId;


                return await service.Update(entity);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="input">过滤条件</param>
        /// <returns></returns>
        public async Task<List<CustomerloandetailEntity>> GetList(CustomerloandetailListQueryInput input)
        {
            try
            {
                return await service.GetList(input);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }


    }
}